package aliyun

import (
	"encoding/json"
	"errors"
	"log/slog"
	"strings"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)

type SmsSvc struct {
	RegionId        string `json:"regionId"`
	AccessKeyId     string `json:"accessKeyId"`
	AccessKeySecret string `json:"accessKeySecret"`
	client          *sdk.Client
}

func (svc *SmsSvc) GetClient() (*sdk.Client, error) {
	if svc.client == nil {
		var client = &sdk.Client{}
		err := client.InitWithAccessKey(svc.RegionId, svc.AccessKeyId, svc.AccessKeySecret)
		if err != nil {
			slog.Error(err.Error())
			return nil, err
		}
		svc.client = client
	}
	return svc.client, nil
}

func (svc *SmsSvc) Send(signName, phoneNumber, templateCode, templateParam string) error {
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Scheme = "https" // https | http
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["RegionId"] = svc.RegionId
	request.QueryParams["SignName"] = signName
	request.QueryParams["PhoneNumbers"] = phoneNumber
	request.QueryParams["TemplateCode"] = templateCode
	request.QueryParams["TemplateParam"] = templateParam

	client, err := svc.GetClient()
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	response, err := client.ProcessCommonRequest(request)
	if err != nil {
		slog.Error(err.Error())
		return err
	}

	type Result struct {
		Code      string `json:"Code"`
		Message   string `json:"Message"`
		BizId     string `json:"BizId"`
		RequestId string `json:"RequestId"`
	}
	var result Result
	if err := json.Unmarshal(response.GetHttpContentBytes(), &result); err != nil {
		slog.Error(err.Error())
		return err
	}
	if strings.ToUpper(result.Code) != "OK" {
		slog.Error(response.GetHttpContentString())
		return errors.New(result.Message)
	}

	slog.Debug("sms has been sent", "response", response.GetHttpContentString())
	return nil
}
